CODE 15. Pascal's Triangle

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/09/16/2013-09-16-CODE 15 Pascal's Triangle/

访问原文「CODE 15. Pascal's Triangle

Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
My Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public ArrayList<ArrayList<Integer>> generate(int numRows) {
// Start typing your Java solution below
// DO NOT write main() function
if (numRows <= 0) {
return new ArrayList<ArrayList<Integer>>();
}
ArrayList<ArrayList<Integer>> pascalsTriangle = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> layer = new ArrayList<Integer>();
layer.add(1);
pascalsTriangle.add(layer);
for (int i = 1; i < numRows; i++) {
ArrayList<Integer> layeri = new ArrayList<Integer>();
ArrayList<Integer> layerj = pascalsTriangle.get(i - 1);
layeri.add(1);
for (int j = 1; j <= i; j++) {
if (j == i) {
layeri.add(1);
} else {
layeri.add(layerj.get(j) + layerj.get(j - 1));
}
}
pascalsTriangle.add(layeri);
}
return pascalsTriangle;
}
Jerky Lu wechat
欢迎加入微信公众号